


//
//  StatusDAL.m
//  kuangjia
//
//  Created by kakao on 16/1/26.
//  Copyright © 2016年 ZhangShuai. All rights reserved.
//

#import "UserAccount.h"
#import "FMDB.h"
#import "UserAccountTool.h"
#import "FMDatabaseQueue.h"
#import "NetworkTools.h"
// 数据库缓存时间长度
static const NSTimeInterval  dbCacheDateTime = 30;
#import "StatusDAL.h"

@implementation StatusDAL

+(void)clearDatabaseCache{

    NSDate  *date=[[NSDate alloc] initWithTimeIntervalSinceNow:-dbCacheDateTime];
    
    
    NSDateFormatter *df=[NSDateFormatter new];
     df.dateFormat=@"yyyy-MM-dd HH:mm:ss";
    
    NSLocale*usLocale=[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
    df.locale=usLocale;
    
    NSString  *dateString=[df stringFromDate:date];
    
    
    NSLog(@"dateString%@",dateString);
    
    // 2. 执行清除缓存的代码
    /*
     -- 测试删除语句时，先用 SELECT 确认满足条件的记录能否被查到
     -- 如果直接用 DELETE 会看不到结果，而且容易误删除数据
     */
    
    NSString  *sql=[NSString stringWithFormat:@"DELETE FROM T_Status WHERE createTime < '%@';",dateString];
    
    NSLog(@"删除sql---%@",sql);
    [[SQliteManager shareInstance].queue inDatabase:^(FMDatabase *db) {
        
        [db executeUpdate:sql];
        NSLog(@"删除成功");
    }];
 
}

/// 数据访问层加载数据
/// 从数据库&网络加载

+(void)loadStatusSince_id:(NSInteger)since_id max_id:(NSInteger)max_id completionBlock:(completionBlock)completionBlock{

    //1.检测本地是否有缓存数据
    NSArray  *list =[ self loadCacheDatasince_id:since_id max_id:max_id];

    if (list.count) {
        completionBlock(list);
        return;
    }
    //3.没有缓存数据  去网络加载数据
[[[NetworkTools sharedTools] loadStatussince_id:since_id max_id:max_id] subscribeNext:^(id result) {
    
    NSArray  *array=result[@"statuses"];
    if (array.count>0) {
        [self saveStatus:array];
        completionBlock(array);
    }
    
    
} error:^(NSError *error) {
    NSLog(@"error----%@",error);
} completed:^{
    NSLog(@"信号完成");
}];
    
}




/// 加载缓存数据
/// 1. 确定参数 since_id 下拉刷新 max_id 上拉刷新
/// 2. 确定 SQL
/// 3. 执行 SQL，返回数据

+(NSArray*)loadCacheDatasince_id:(NSInteger)since_id max_id:(NSInteger)max_id {

    
     NSString *userId =[UserAccountTool loadUserAccount].uid;
    
    NSString *sql =[NSString stringWithFormat:@"SELECT statusId, status, userId FROM T_Status \n WHERE userId=%@\n",userId];
    // 根据参数，调整查询条件

    if (since_id>0) {
         // 下拉刷新
        sql=[NSString stringWithFormat:@"%@AND statusId>%ld\n",sql,since_id];
    }else if (max_id>0){
        sql=[NSString stringWithFormat:@"%@AND statusId <%ld\n",sql,max_id];
    
    }
    sql=[NSString stringWithFormat:@"%@ORDER BY statusId DESC LIMIT 20;",sql];
     // 继续之前，一定记住测试
    
    NSLog(@"%@",sql);
    
    NSMutableArray *array=[NSMutableArray array];
    [[SQliteManager shareInstance].queue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *rs=[db executeQuery:sql];
        if (rs) {
            
            while (rs.next) {
                
                NSString *jsonString=[rs stringForColumn:@"status"];
                // 反序列化

                NSData  *data =[jsonString dataUsingEncoding:NSUTF8StringEncoding];
                NSError *error = nil;
                NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
                
                [array addObject:dict];
            }
        }
        
    }];
    return array;
    
}


/// 将数据保存到数据库
/// 1. 确定一下参数 - 从网络获取到的`字典`数组
/// 2. 确定 SQL
/// 3. 利用数据库工具，遍历数组，顺序插入数据

//    NSString *sql =[NSString stringWithFormat:@"SELECT statusId, status, userId FROM T_Status \n WHERE userId = %@\n",userId];


+ (void)saveStatus:(NSArray *)status
{
    
//    assert([UserAccountTool userLogon],@"必须登录才能使用");
    
    NSString *userId =[UserAccountTool loadUserAccount].uid;
    
    NSString *sql=[NSString stringWithFormat:@"INSERT OR REPLACE INTO T_Status (statusId, status, userId) VALUES (?, ?, ?);"];
    
    [[SQliteManager shareInstance].queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
         // 1. 遍历数组
        
        for (NSDictionary *dict in status) {
            // 1> 微博代号

            NSString * staid =dict[@"id"];
            NSInteger statusId= [staid integerValue];
            NSData* json=  [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
            
       
            NSString *jsonString =[[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
            
            
            
          // 3> 插入数据
//            if ([db executeUpdate:[NSString stringWithFormat:@"%@%ld%@%@",sql,statusId,jsonString,userId]]) {
//                
//                *rollback=YES;
//                break;
//            }
            
//            if (![db executeUpdateWithFormat:@"%@%ld%@%@",sql,statusId,jsonString,userId]) {
//                
//                                *rollback=YES;
//                                break;
//
//            }
            
            if (![db executeUpdate:sql withArgumentsInArray:@[@(statusId),jsonString,userId]]) {
                *rollback=YES;
               break;

            }
//
        }
        
        NSLog(@"保存了%ld条记录",status.count);
        
    }];
    
}


@end
